<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/main/department' }">权限管理</el-breadcrumb-item>
          <el-breadcrumb-item>部门管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-row>
      <el-row><br><br></el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="19">
          <el-form :inline="true" :model="dto" class="form-inline" ref="dtoForm">
            <el-form-item prop="name">
              <el-input v-model="dto.name" placeholder="请输入部门名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-date-picker
              v-model="timeValue"
              type="daterange"
              range-separator="至"
              start-placeholder="请选择添加时间"
              end-placeholder="请选择添加时间"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
            </el-form-item>
            <el-form-item prop="state">
              <el-select v-model="dto.state" clearable placeholder="请选择运行状态">
                <el-option label="正常" value="1"></el-option>
                <el-option label="锁定" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-form>         
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="15">
          <el-button type="primary" icon="el-icon-search" @click="getDepartmentList()">搜索</el-button>
          <el-button type="warning" @click="resetForm('dtoForm')">重置</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" round @click="handleAdd()">添加部门</el-button>
        </el-col>
      </el-row>
      <el-row><br><br></el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="22">
          <el-table
            :data="departmentList"
            style="width: 100%">
            <el-table-column
              label="序号"
              type="index"
              width="60">
            </el-table-column>
            <el-table-column
              prop="name"
              label="部门名称"
              width="120">
            </el-table-column>
            <el-table-column
              prop="num"
              label="成员数量"
              width="120">
            </el-table-column>
            <el-table-column
              prop="time"
              label="添加时间"
              width="200"
              :formatter="formatDateToYMD">
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.state == 1" type="success">正常</el-tag>
                <el-tag v-else type="danger">锁定</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope"> 
                <el-button
                  size="mini" type="primary" icon="el-icon-edit"
                  @click="handleEdit(scope.row)">编辑</el-button>
                <el-button
                  size="mini" v-if="scope.row.state == 1" type="warning"
                  :disabled = "scope.row.num > 0 "
                  @click="handleDisable(scope.row)">锁定</el-button>
                <el-button
                  size="mini" v-if="scope.row.state == 0" type="success"
                  @click="handleEnable(scope.row)">解锁</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  :disabled = "scope.row.num > 0 "
                  @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="5">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="dto.page"
            :page-size="dto.size"
            layout="total, prev, pager, next"
            :total="total">
          </el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表单弹出框 -->
    <el-dialog :title="formtitle" :visible.sync="dialogDepartmentVisible" width="30%" @close="close('ruleForm')"  :modal-append-to-body="false">
      <el-form :model="department" :rules="currentRules" ref="ruleForm">
        <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="department.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validateCheckName = (rule, value, callback) => {
      if (this.formtitle == '编辑部门' && this.department.name == this.oldDepratment.name ){
        callback(new Error('请修改部门名称'));
      } else {
        this.$axios.get('/department/checkName/' + value).then(res=>{
        if (res.data.code == 200) {
          if (res.data.data) {
            callback();
          } else {
            callback(new Error('您输入的名称已存在'));
          }
        }
      })
      }
    };
    return {
      dto:{
        name:"",
        startTime:'',
        endTime:'',
        state:'',
        page:1,
        size:5
      },
      timeValue: '',
      departmentList:[],
      total: 0,
      dialogDepartmentVisible: false,
      formtitle: '',
      formLabelWidth: '80px',
      department:{
        id:'',
        name:''
      },
      OldDepartment:{
        name:''
      },
      currentRules:{},
      ruleAdd:{
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { validator: validateCheckName, trigger: 'blur' }
        ],
      },
      ruleEdit:{
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { validator: validateCheckName, trigger: 'blur' }
        ],
      }
    }
  },
  watch:{
     // 监听title的变化，动态切换规则集
     formtitle(newTitle) {
      this.currentRules = newTitle === '添加部门' ? this.ruleAdd : this.ruleEdit;
      // 如果需要，可以在这里触发表单的重新验证
      // this.$refs.ruleForm.validate();
    }
  },
  mounted() {
    this.getDepartmentList()
  },
  methods: {
    handleCurrentChange(val){
      this.dto.page = val
      this.getDepartmentList()
    },
    //重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.timeValue = ''
    },
    getDepartmentList(){
      this.dto.startTime = this.timeValue[0]
      this.dto.endTime = this.timeValue[1]
      this.$axios.get('/department/getDepartmentList',{
        params:this.dto
      }).then(res=>{
        this.departmentList = res.data.data.data
        this.total = res.data.data.total
      })
    },
    formatDateToYMD(row, column, value) {
      // 如果value是有效的日期时间字符串，可以使用以下方式直接格式化
      if (value) {
        const date = new Date(value);
        const year = date.getFullYear();
        const month = this.padZero(date.getMonth() + 1); // 月份是从0开始的，所以加1
        const day = this.padZero(date.getDate());
        const hours = this.padZero(date.getHours());
        const minutes = this.padZero(date.getMinutes());
        const seconds = this.padZero(date.getSeconds());
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      return '';
    },
    padZero(num) {
      return num < 10 ? '0' + num : num; // 用于补零操作，保证日期格式为两位数
    },
    close(formName){
      this.$refs[formName].clearValidate();
      this.dialogDepartmentVisible = false
    },
    handleAdd(){
      this.dialogDepartmentVisible = true
      this.formtitle = "添加部门"
      this.department = {
        name:''
      }
    },
    handleEdit(row){
      this.oldDepratment = {
        name: row.name
      }
      this.dialogDepartmentVisible = true
      this.formtitle = "编辑部门"
      this.department = {
        id: row.id,
        name: row.name
      }
    },
    handleConfirm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formtitle == '添加部门') {
            this.$axios.post('/department/addDepartment',this.department).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                this.dialogDepartmentVisible = false
                this.getDepartmentList()
              }
            })
          }
          if (this.formtitle == '编辑部门') {
            this.$axios.put('/department/editDepartment',this.department).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  message: '编辑成功！',
                  type: 'success'
                });
                this.dialogDepartmentVisible = false
                this.getDepartmentList()
              }
            })
          }     
        } else {
          return false;
        }
      }); 
    },
    handleEnable(row){
      this.$axios.put('/department/enableDepartment/' + row.id).then(res=>{
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: '启用成功!'
          });
          this.getDepartmentList()
        }
      })
    },
    handleDisable(row){
      this.$axios.put('/department/disableDepartment/' + row.id).then(res=>{
        if (res.data.code == 200) {
          if (res.data.data) {
            this.$message({
              type: 'success',
              message: '锁定成功!'
            });
            this.getDepartmentList()
          }        
        }
      })
    },
    handleDelete(row){
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/department/deleteDepartment/' + row.id).then(res=>{
          if (res.data.code == 200) {
            if (res.data.data){
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getDepartmentList()
            }
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
}
</script>

<style scoped>

.box-card {
  margin-left:5vh;
  margin-right:2vh;
  margin-top: 3vh;
  height: 88vh;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

</style>